//
//  YSGRegisterViewController.swift
//  EyeVisionForPatients
//
//  Created by liuyutian on 2023/2/16.
//  Copyright © 2023 QDSG. All rights reserved.
//

import UIKit

class YSGRegisterViewController: BaseViewController,UITableViewDelegate,UITableViewDataSource {
     @IBOutlet weak var tableView: UITableView!

   var model = RegisterModel() {
        didSet {
            tableView.reloadData()
        }
    }
    @IBAction func agreementAction(_ sender: UIButton) {
        let agreementView = UINib.loadViewFrom(AgreementAlertView.self)
        agreementView.show(type: .appLawAndPrivacy)
    }
    
    @IBAction func acreeButtonAction(_ sender: UIButton) {
        sender.isSelected.toggle()
    }
    @IBOutlet weak var agreeButton: UIButton!
    @IBAction func registerAction(_ sender: Any) {
        
        
        view.endEditing(true)
        if !agreeButton.isSelected {
            HUDTool.show(message: "请阅读并同意《法律声明及隐私权协议》")
            return
        }
        
        if model.name.isEmpty {
            HUDTool.show(message: "姓名不能为空")
            return
        }
        
        if model.phone.isEmpty {
            HUDTool.show(message: "请填写手机号")
            return
        }
        
        if !model.phone.isPhone() {
            HUDTool.show(message: "请填写正确的手机号")
            return
        }
        
        if model.code.isEmpty {
            HUDTool.show(message: "请输入验证码")
            return
        }
        
        if model.password.isEmpty {
            HUDTool.show(message: "请设置登录密码")
            return
        }
        
        if model.repassword.isEmpty {
            HUDTool.show(message: "请确认登录密码")
            return
        }
        
        if model.password != model.repassword {
            HUDTool.show(message: "登录密码两次输入不一样")
            return
        }
        
        model.checkRegistered(success: { [weak self] in
            self?.register()
        }) { errorMsg in
            HUDTool.showError(message: errorMsg)
        }
    }
    
    @IBAction func backAction(_ sender: Any) {
        dismiss(animated: true)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let bgLayer1 = CAGradientLayer()
        bgLayer1.colors = [UIColor(hex: "#E2ECFF").cgColor, UIColor(red: 246/255.0, green: 248/255.0, blue: 253/255.0, alpha: 0.7).cgColor, UIColor(hex: "#FFFFFF").cgColor]
        bgLayer1.locations = [0, 0.34, 1]
        
        let backview = UIView(frame: (AppDelegate.share()?.window!.frame)!)
        view.addSubview(backview)
        bgLayer1.frame = (AppDelegate.share()?.window!.frame)!
        backview.layer.addSublayer(bgLayer1)

        view.sendSubviewToBack(backview)
        
        tableView.delegate = self
        tableView.dataSource = self
        tableView.isScrollEnabled = false
        setupData()
        setupNavBar()
        setupUI()
        
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return model.numberOfRows
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = RegisterFormCell.init()
        var row = 0
        if model.isCheck {
            row = indexPath.row >= 1 ? indexPath.row + 3 : indexPath.row
        } else {
            row = indexPath.row
        }
        let cellType = RegisterFormCellType(rawValue: row) ?? .name
        cell.configure(with: model, cellType: cellType)
        cell.delegate = self
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        var row = 0
        if model.isCheck {
            row = indexPath.row >= 1 ? indexPath.row + 3 : indexPath.row
        } else {
            row = indexPath.row
        }
        let cellType = RegisterFormCellType(rawValue: row) ?? .name
        
        if cellType == .area {
            let addressVc = AddressViewController()
            addressVc.modalPresentationStyle = .custom
            addressVc.chooseClosure = { [weak self] model in
                guard let self = self else { return }
                self.model.area = "\(model.provinceName) \(model.cityName) \(model.areaName)"
                self.model.provinceId = model.provinceId
                self.model.cityId = model.cityId
                self.model.regionId = model.areaId
                self.tableView.reloadData()
            }
            present(addressVc, animated: true) {
                addressVc.view.backgroundColor = UIColor.black.withAlphaComponent(0.36)
            }
        }
    }
}



extension YSGRegisterViewController: RegisterFormCellDelegate {
    func register(didSendSmsCode cell: RegisterFormCell) {
        model.sendSmsCode(success: {
            HUDTool.show(message: "短信发送成功")
        }) { errorMsg in
            cell.resetCodeBtn()
            HUDTool.showError(message: errorMsg)
        }
    }
    
    func register(_ cell: RegisterFormCell, didEndEditing model: RegisterModel) {
        switch cell.cellType {
        case .idCard:
            if model.idCard.isEmpty {
//                HUDTool.show(message: "身份证不能为空")
            } else if !model.idCard.isValidateIdCard() {
                HUDTool.show(message: "身份证格式错误")
            }
        case .phone:
            if model.phone.isEmpty {
                HUDTool.show(message: "手机号不能为空")
            } else if !model.phone.isPhone() {
                HUDTool.show(message: "手机号格式错误")
            }
        default: break
        }
        self.model = model
    }
    
    func register(didStartRegister cell: RegisterFormCell) {

    }
    
    private func register() {
        model.register(success: { [weak self] in
            HUDTool.show(message: "注册成功")
            self?.navigationController?.dismiss(animated: true)
        }) { errorMsg in
            HUDTool.showError(message: errorMsg)
        }
    }
}

extension YSGRegisterViewController {
    private func setupData() {

        
        self.model.isCheck = true
        self.model.titles = ["姓名", "手机号", "验证码", "登录密码", "确认密码"]
        self.tableView.reloadData()
    }
    
    private func setupNavBar() {
        title = "注册"
        let leftItem = UIBarButtonItem(imageName: "nav_back", target: self, action: #selector(dismissTo))
        navigationItem.leftBarButtonItem = leftItem


    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.alpha = 0.0
        self.navigationController?.navigationBar.isTranslucent = true
    }
    
    
 
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

    }
    
    private func setupUI() {
        
        let layerView = UIView()
        layerView.frame =  CGRect(x: 16, y: tableView.frame.origin.y, width: screenW - 32, height: 378)
        // strokeCode
        let borderLayer1 = CALayer()
        borderLayer1.cornerRadius = 12
        borderLayer1.borderColor = UIColor.white.cgColor
        borderLayer1.borderWidth = 1
        borderLayer1.frame = layerView.bounds
        borderLayer1.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1).cgColor
        layerView.layer.addSublayer(borderLayer1)
        let bgLayer1 = CAGradientLayer()
        bgLayer1.colors = [UIColor(red: 0.96, green: 0.97, blue: 1, alpha: 0.8).cgColor, UIColor(red: 1, green: 1, blue: 1, alpha: 0.8).cgColor]
        bgLayer1.locations = [0, 1]
        bgLayer1.frame = CGRect(x: 1, y: 1, width: 341, height: 362)
        bgLayer1.startPoint = CGPoint(x: 0.5, y: 0)
        bgLayer1.endPoint = CGPoint(x: 1, y: 1)
        
        layerView.layer.addSublayer(bgLayer1)
        
        view.addSubview(layerView)
        view.sendSubviewToBack(layerView)
        
        
        tableView.backgroundColor = UIColor.clear
        tableView.keyboardDismissMode = .onDrag
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        tableView.tableFooterView = UIView()

        tableView.register(RegisterFormCell.self, forCellReuseIdentifier: RegisterFormCell.reuseIdentifier)
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
        tap.cancelsTouchesInView = false
        tableView.addGestureRecognizer(tap)
    }
    
    @objc private func dismissKeyboard() {
        tableView.endEditing(true)
    }
    
    @objc private func dismissTo() {
        dismiss(animated: true)
    }
}
